package ar.com.coonocer.joy.mdg.util.templating.gsp;

import groovy.lang.Writable;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil {

	private static Log logger = LogFactory.getLog(FileUtil.class);

	public static void saveResponseToFile(byte[] binaryData, File destinationFile) {
		destinationFile.getParentFile().mkdirs();
		//
		BufferedOutputStream writer = null;
		try {
			writer = new BufferedOutputStream(new FileOutputStream(destinationFile));
			writer.write(binaryData);
			writer.flush();
		} catch (IOException e) {
			throw new RuntimeException("Cannot write generated content to file:" + destinationFile, e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					logger.debug("Error closing output file", e);
				}
			}
		}
	}

	public static void saveResponseToFile(Writable writable, File destinationFile) {
		destinationFile.getParentFile().mkdirs();
		//
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(destinationFile));
			writable.writeTo(writer);
			writer.flush();
		} catch (IOException e) {
			throw new RuntimeException("Cannot write generated content to file:" + destinationFile, e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					logger.debug("Error closing output file", e);
				}
			}
		}
	}

}
